/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cong.javadanang.model.dao.impl;

import cong.javadanang.model.dao.RoleDAO;
import cong.javadanang.model.entity.Role;
import cong.javadanang.model.entity.User;
import hibernate.HibernateUtil;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Pham
 */
public class RoleDAOImpl implements RoleDAO {

    private static RoleDAOImpl roleDAO;

    public static RoleDAOImpl getInstance() {
        if (roleDAO == null) {
            roleDAO = new RoleDAOImpl();
        }
        return roleDAO;
    }

    private Session session;
    private Transaction ts;

    @Override
    public Role getRoleById(int roleId) {
        session = HibernateUtil.getSessionFactory().openSession();
        Role role = null;
        try {
            ts = session.beginTransaction();
            role = (Role) session.get(Role.class, roleId);
            List<User> users = session.createQuery("FROM User as u Where u.role = :role")
                    .setParameter("role", role).list();
            role.setUsers(users);
            ts.commit();
        } catch (HibernateException e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
        }finally{
            session.close();
        }
        return role;
    }

    @Override
    public List<Role> getRoles() {
        session = HibernateUtil.getSessionFactory().openSession();
        List<Role> roles = null;
        try {
            ts = session.beginTransaction();
            String sql = "FROM Role";
            Query query = session.createQuery(sql);
            roles = query.list();
            for (Role role : roles) {
                List<User> users = session.createQuery("FROM User as u Where u.role = :role")
                        .setParameter("role", role).list();
                role.setUsers(users);
            }
            ts.commit();
        } catch (HibernateException e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
        }finally{
            session.close();
        }
        return roles;
    }

}
